package com.example.chat.controller;

import com.example.chat.pojo.Result;
import com.example.chat.pojo.User;
import com.example.chat.service.EmailService;
import com.example.chat.service.UserService;
import com.example.chat.utils.JwtUtil;
import com.example.chat.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:8080")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostMapping("/register")
    public Result register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String email,
                           @RequestParam String verificationCode) {
        System.out.println("Received parameters: " + username + ", " + password + ", " + email + ", " + verificationCode);

//    // 从数据库获取验证码
//    String storedCode = userService.getVerificationCodeByEmail(email);
//    if (storedCode == null || !storedCode.equals(verificationCode)) {
//        return Result.error("验证码错误或已过期");
//    }

// 从 Redis 获取验证码
        String storedCode = userService.getVerificationCodeByEmail(email);
        if (storedCode == null || !storedCode.equals(verificationCode)) {
            return Result.error("验证码错误或已过期");
        }

        User existingUser = userService.findByEmail(email);
        if (existingUser != null) {
            return Result.error("该邮箱已被注册");
        }
        User user = userService.findByUserName(username);
        if (user == null) {
            // 注册用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(Md5Util.getMD5String(password));
            newUser.setEmail(email);
            newUser.setTokens(20000);
            userService.addUser(newUser);
            return Result.success();
        } else {
            return Result.error("用户名已经被占用");
        }
    }


    @PostMapping("/verifyCode")
    public Result<String> verifyCode(@RequestParam String username,
                                     @RequestParam String verificationCode) {
        // 获取用户的邮箱
        User user = userService.findByUserName(username);
        if (user == null) {
            return Result.error("用户名不存在");
        }

        // 验证验证码
        boolean isVerified = userService.verifyCode(user.getEmail(), verificationCode);
        if (isVerified) {
            userService.activateUser(username); // 激活用户
            return Result.success("注册成功");
        } else {
            return Result.error("验证码错误或已过期");
        }
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> payload) {
        String username = payload.get("username");
        String password = payload.get("password");

        // 查询用户信息
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("用户名错误");
        }

        // 验证密码
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            // 创建包含用户信息的 claims
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());

            // 生成 JWT 令牌
            String token = JwtUtil.genToken(claims);

            // 准备返回的数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("user", loginUser);

            // 返回成功结果，包括 token 和用户信息
            return Result.success(responseData);
        }

        // 如果密码错误
        return Result.error("密码错误");
    }

    @PostMapping("/sendCode")
    public Result<String> sendCode(@RequestParam String email) {
        // 分割并去重邮箱地址（如果是逗号分隔的多个地址）
        Set<String> emailSet = new HashSet<>(Arrays.asList(email.split(",")));

        // 确保只有一个有效的邮箱
        if (emailSet.size() != 1) {
            return Result.error("请输入一个有效的邮箱地址");
        }

        String uniqueEmail = emailSet.iterator().next().trim(); // 去掉前后空格
        String lastSentTime = redisTemplate.opsForValue().get(uniqueEmail + ":lastSentTime");
        // 检查是否在一分钟内已经发送过验证码
        long currentTime = System.currentTimeMillis();

        if (lastSentTime != null) {
            long lastTime = Long.parseLong(lastSentTime);
            long timeDiff = currentTime - lastTime;
            System.out.println("时间差: " + timeDiff + " 毫秒");

            // 检查是否在1分钟内
            if (timeDiff < 60000) {
                System.out.println("验证码发送过于频繁，请稍后再试。");
                return Result.error("验证码发送过于频繁，请稍后再试。");
            }
        }
        // 生成验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        System.out.println("生成的验证码: " + code);

        // 发送验证码
        try {

            emailService.sendEmail(uniqueEmail, "验证码", "您的验证码是：" + code);
            System.out.println("验证码已发送到: " + uniqueEmail); // 这里只打印唯一的邮箱
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("验证码发送失败");
        }

        // 将验证码存储到数据库
        try {
            userService.saveVerificationCode(uniqueEmail, code);
            redisTemplate.opsForValue().set(uniqueEmail + ":lastSentTime", String.valueOf(currentTime), 10, TimeUnit.MINUTES);

            String savedCode = userService.getVerificationCodeByEmail(uniqueEmail);
            if (savedCode == null || !savedCode.equals(code)) {
                throw new Exception("验证码保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("验证码保存失败");
        }

        return Result.success("验证码已发送，请检查您的邮箱。");
    }

    @GetMapping("/tokens")
    public Result<Integer> getTokens(@RequestParam String username) {
        User user = userService.findByUserName(username);
        if (user != null) {
            return Result.success(user.getTokens());
        } else {
            return Result.error("User not found");
        }
    }
    @GetMapping("/userInfo")
    public Result<Map<String, Object>> getUserInfo(@RequestParam String username) {
        // 根据用户名查找用户
        User user = userService.findByUserName(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 创建包含用户信息的 Map
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", user.getUsername());
        userInfo.put("email", user.getEmail());
        userInfo.put("tokens", user.getTokens());
        userInfo.put("password", user.getPassword());

        // 返回包含用户信息的结果
        return Result.success(userInfo);
    }

}
